package com.zhangye.test.util;


public class NumberTranscoder {

    private NumberTranscoder() {
    }

    public static byte[] fixBytes(byte[] rv) {
        int skip = 0;
        for (; skip < rv.length && rv[skip] == 0; skip++)
            ;
        if (skip > 0) {
            byte[] tmp = new byte[rv.length - skip];
            System.arraycopy(rv, skip, tmp, 0, rv.length - skip);
            rv = tmp;
        }
        return rv;
    }

    public static byte[] encode(long l, int maxBytes) {
        byte[] rv = new byte[maxBytes];
        for (int i = 0; i < rv.length; i++) {
            int pos = rv.length - i - 1;
            rv[pos] = (byte) ((l >> (8 * i)) & 0xff);
        }
        return rv;
    }

    public static byte[] encodeFix(long l, int maxBytes) {
        return fixBytes(encode(l, maxBytes));
    }

    public static long decodeLong(byte[] b) {
        long rv = 0;
        for (byte i : b) {
            rv = (rv << 8) | (i < 0 ? 256 + i : i);
        }
        return rv;
    }

    public static byte[] encodeInt(int in) {
        return encodeFix(in, 4);
    }

    public static int decodeInt(byte[] in) {
        return (int) decodeLong(in);
    }
}
